//cart页面入口文件
import '../css/cart.scss';

//组件：
//引入header模块(构造函数)
import Header from '../components/header/index.js';
//引入ListItem模块(构造函数)
import ListItem from '../components/cart/list_item/index.js';
//引入PurchaseBox模块(构造函数)
import PurchaseBox from '../components/cart/purchase_box/index.js';
//引入NoListTip模块(构造函数)
import NoListTip from '../components/cart/no_list_tip/index.js';
//引入Toast模块(构造函数)
import Toast from '../components/toast/index.js';

//数据：
//导入数据模型的类
import {
  CartModel
} from '../models/cart';

//实例化引入组件模块
const header = new Header();
const listItem = new ListItem();
const purchaseBox = new PurchaseBox();
const noListTip = new NoListTip();
const toast = new Toast();

//初始化节点
const doms = {
  oMainCheck: null,
  oSubChecks: null,
  oEditBtn: null,
  oPurchaseBtn: null,
  oPurchaseBox: null,
  oTotal: null
}

//实例化数据模型的类
const cartModel = new CartModel();

//入口文件
const App = (doc) => {
  //获取主页container容器
  const oContainer = doc.getElementsByClassName('J_container')[0],
    oList = oContainer.getElementsByClassName('J_list')[0];

  //缓存用户数据，避免多次请求数据
  let cartInfos = {
    //列表数据
    list: [],
    //总价格
    total: 0
  }

  const init = () => {
    //初始化时就插入header组件到主页
    oContainer.appendChild(header.tpl('购物车管理', true));
    //根据用户id获取购物车信息
    cartModel.getCartList(1)
      .then((res) => {
        cartInfos.total = res.total_price;
        cartInfos.list = res.res;

        if (res.res) {
          oList.innerHTML = listItem.makeList(cartInfos.list);
          //插入购买盒子节点并向子组件传入总价格数据
          oContainer.appendChild(purchaseBox.tpl(cartInfos.total));
        } else {
          oList.innerHTML = noListTip.tpl();
        }
      })
      //加载完页面数据后绑定事件
      .then(() => {
        bindEvent();
      })
  }

  //父级事件委托绑定
  //针对子组件listItem
  const bindEvent = () => {

    doms.oMainCheck = doc.getElementsByClassName('J_mainCheck')[0],
      doms.oEditBtn = doc.getElementsByClassName('J_editItem')[0],
      doms.oPurchaseBtn = doc.getElementsByClassName('J_purchaseBtn')[0];


    oList.addEventListener('click', listEvent, false);
    //绑定购物车商品单选框点击事件
    doms.oMainCheck && doms.oMainCheck.addEventListener('click', onMainCheck, false);
    //绑定标题上的编辑按钮点击事件
    doms.oEditBtn.addEventListener('click', header.onEditBth, false);
    doms.oPurchaseBtn && doms.oPurchaseBtn.addEventListener('click', purchaseCart, false);
  }

  //numOperation操作购买数量的方法
  const listEvent = (e) => {
    // //阻止默认行为
    // e.preventDefault();

    //逻辑代码交给子组件
    //then()接收子组件promise抛出的数据
    listItem.listEvent(e).then((res) => {
      if (res !== -1) {
        doms.oTotal = oContainer.getElementsByClassName('J_totalPrice')[0];

        // console.log(res);
        //{field: "checkBox", idx: "0", checked: false}
        //{field: "numSelector", num: "3", idx: "1"}

        let item = cartInfos.list[res.idx];
        // console.log(item);
        /**
         * {
         *   "id": "45",
         *   "uid": "1",
         *   "total_num": "2",
         *   "num": "2",
         *   "total_price": "4598",
         *   "goods_id": "8",
         *   "add_time": "1627486529",
         *   "status": "1", 
         *   "goods_name": "Huawei/华为 nova4e AI超广角三摄全面屏正品智能关晓彤代言手机nova4e",
         *   "price": "2299",
         *   "img_url": "http://imgtest.jsplusplus.com/phones/8.jpg",
         *   "limitation": "2",
         *   "checked": true
         * }
         */

        switch (res.field) {
          case 'numSelector':
            numOperation(item, res);
            break;
          case 'checkBox':
            itemCheck(item, res);
            break;
          case 'remove':
            removeItem(res.id);
            break;
          default:
            break;
        }
      }
    })
  }

  //计算总价
  const numOperation = (item, data) => {
    // console.log(data);
    // {field: "numSelector", num: "1", idx: "2"}

    doms.oSubChecks = doc.getElementsByClassName('J_subCheck');

    item.num = data.num;
    item.total_price = data.num * item.price;

    //点击该项商品里面的 +/- 更新信息时会勾选 单选框
    doms.oSubChecks[data.idx].checked = true;
    cartInfos.list[data.idx].checked = true;
    reComputeTotal();
  }

  //单击购物车商品单选框确定/取消会实时更新总价
  const itemCheck = (item, data) => {
    item.checked = data.checked;
    reComputeTotal();
  }

  //点击购物车商品右侧删除按钮 删除该条商品数据
  const removeItem = (id) => {
    const list = cartInfos.list;

    for (let i = 0; i < list.length; i++) {
      const item = list[i];
      if (item.id === id) {
        const idx = list.indexOf(item);
        cartInfos.list.splice(idx, 1);
        break;
      }
    }

    if (cartInfos.list.length > 0) {
      reComputeTotal();
    } else {
      const oPurchaseBox = doc.getElementsByClassName('purchase-box')[0];
      oPurchaseBox.remove();
      oList.innerHTML = noListTip.tpl();
    }
  }

  //单击购物车商品项的 单选框按钮 打勾/不打勾 全选/不全选功能
  const onMainCheck = () => {
    doms.
    oSubChecks = doc.getElementsByClassName('J_subCheck'),
      doms.oMainCheck = doc.getElementsByClassName('J_mainCheck')[0];

    Array.from(doms.oSubChecks).forEach((elem, index) => {
      elem.checked = doms.oMainCheck.checked;
      cartInfos.list[index].checked = doms.oMainCheck.checked;
    });

    reComputeTotal(!doms.oMainCheck.checked && true);
  }

  const reComputeTotal = (doZero) => {
    doms.oTotal = oContainer.getElementsByClassName('J_totalPrice')[0];

    //清空
    cartInfos.total = 0;

    if (doZero) {
      doms.oTotal.innerHTML = 0;
      return;
    }

    //重新遍历看是否全选
    cartInfos.list.forEach((elem) => {
      if (elem.checked) {
        cartInfos.total += Number(elem.total_price);
      }
    });
    doms.oTotal.innerHTML = cartInfos.total;
  }

  //购物车：购买功能
  const purchaseCart = () => {
    let gids = [];
    cartInfos.list.forEach((elem) => {
      if (elem.checked) {
        gids.push(elem.id);
      }
    });

    cartModel.purchaseCart(1, gids.toString())
      .then((res) => {
        doms.oTotal = oContainer.getElementsByClassName('J_totalPrice')[0],
          doms.oPurchaseBox = doc.getElementsByClassName('purchase-box')[0],
          doms.oMainCheck = doc.getElementsByClassName('J_mainCheck')[0];

        const code = res.msg_code;

        if (code === '200') {
          toast.showToast({
            icon: 'success',
            title: '支付成功',
            duration: 1500
          });

          gids.forEach((val) => {
            cartInfos.list.forEach((elem, idx) => {
              if (elem.id === val) {
                cartInfos.list.splice(idx, 1);
              }
            })
          });

          if (cartInfos.list.length > 0) {
            oList.innerHTML = listItem.makeList(cartInfos.list);
            doms.oMainCheck.checked = true;
            reComputeTotal();
          } else {
            oList.innerHTML = noListTip.tpl();
            doms.oPurchaseBox.remove();
          }
        } else {
          toast.showToast({
            icon: 'warning',
            title: '支付失败',
            duration: 1500
          });
        }
      })
  }

  init();
}

new App(document);